<template>
    <section>
      <ul class="template-banner-list">
        <li class="banner-item" v-for="(banner,bIndex) in bannerList" :key="bIndex" v-if="banner.deleted=='UN_DELETED'">
          <el-popover
            placement="top"
            width="160"
            v-model="banner.visible">
            <p>确定删除吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="banner.visible = false">取消</el-button>
              <el-button type="primary" size="mini" @click="onItemClose(bIndex)">确定</el-button>
            </div>
            <el-button type="text" icon="el-icon-close" slot="reference" class="banner-close"></el-button>
          </el-popover>
          <el-form>
              <el-form-item label="轮播广告">
                <span>排序:</span>
                <el-input-number size="mini" style="width:50px" v-model="banner.showOrder" :controls="false" :min="1" :max="99" @change="onSortChange"></el-input-number>
              </el-form-item>
            <el-row>
              <el-upload class="banner-uploader"
                :action="uploadAction" :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                <div @click="onUpClick(bIndex)" style="height: 100%">
                  <img v-if="banner.imageUrl" :src="banner.imageUrl" class="banner-image"  />
                  <i v-else class="el-icon-plus banner-uploader-icon" ></i>
                  <p class="default_tips">建议图片尺寸644*260像素，JPG、PNG格式，小于100KB</p>
                </div>
              </el-upload>
            </el-row>
            <el-form-item label="图片标题" label-width="80px">
              <el-input v-model="banner.title" placeholder="(选填)"></el-input>
            </el-form-item>
            <el-form-item label="跳转链接" label-width="80px">
              <el-select v-model="banner.linkText" @change="onLinkChange(banner,bIndex)"
                         filterable
                         allow-create
                         default-first-option placeholder="选择跳转到的页面" style="width:420px;">
                <el-option label="书库" value="1"></el-option>
                <el-option label="自定义链接可直接填写" value="2"></el-option>
              </el-select>
              <!--<el-input placeholder="选择跳转到的页面" v-model="banner.linkUrl" class="input-with-select">-->
                  <!--<el-select v-model="banner.linkType" slot="prepend" placeholder="请选择" style="width:90px;">-->
                    <!--<el-option label="书库" value="1"></el-option>-->
                    <!--<el-option label="自定义" value="2"></el-option>-->
                  <!--</el-select>-->
              <!--</el-input>-->
            </el-form-item>
          </el-form>
        </li>
      </ul>
      <el-row>
        <a class="banner-add" @click="onItemAdd">+添加轮播图片</a><span class="default_tips">(最多可填充10个轮播图)</span>
      </el-row>
      <el-dialog top="2vh" title="跳转链接" :visible.sync="dialogVisible" width="700px" @close="handleClose">
        <select-book :templateId="templateId" @save="emitSave" v-if="dialogVisible"></select-book>
      </el-dialog>
    </section>
</template>

<script>
import { getUploadFileRequest } from "../../../api";
import SelectBook from './SelectBook'
export default {
      name: "Banner",
      props:{
        banners:{
          type:Array,
          default:[]
        },
        templateId:{
          type:String,
          default:null
        }
      },
      data(){
          return{
            bannerList:[],
            template:{
              id:null,
              showOrder:1,
              title:'',
              imageUrl:'',
              linkUrl:'',
              bookId:null,
              linkType:2,
              linkText:'',
              visible:false,
              deleted:'UN_DELETED',
            },
            uploadIndex:-1,
            uploadAction:getUploadFileRequest(),
            dialogVisible:false,
          }
      },
      watch:{
        bannerList:function (value,oldValue) {
          this.autoUpdate();
        }
      },
      components:{SelectBook},
      methods: {
        onItemClose(index){
          this.bannerList[index].visible = false;
          if(this.bannerList[index].id != null){
            this.bannerList[index].deleted = 'DELETED';
          }else {
            this.bannerList.splice(index, 1)
          }
        },
        onItemAdd(){
          if(this.bannerList.length>9){
            this.$alert("最多可填充10个轮播图","提示");
            return;
          }
          let newBanner = this.baseUtil.modelCopy(this.template);
          let list = this.bannerList.filter(m=>m.deleted=='UN_DELETED');
          let maxSort = list.length>0?list[list.length-1].showOrder : 0;
          newBanner.showOrder = maxSort+1;
          this.bannerList.push(newBanner)
        },
        handleClose(){
          let editBanner =  this.bannerList[this.uploadIndex];
          if(this.baseUtil.isNotBlank(editBanner.bookId)){
            editBanner.linkText = editBanner.defaultText;
          }else{
            editBanner.linkText = "";
            editBanner.linkType = 2;
            editBanner.linkUrl = '';
          }
          this.uploadIndex = -1;
        },
        onLinkChange(banner,index){
          switch (banner.linkText) {
            case "1":
              banner.linkType = 1;//选择书库
              // banner.linkUrl = '';
              // banner.linkText = '';
              this.uploadIndex = index;
              this.dialogVisible = true;
              break;
            case "2":
              banner.linkType = 2;
              banner.linkUrl = '';
              banner.linkText = '';
              break;
            default:
              banner.linkType = 2;
              banner.linkUrl = banner.linkText;
              break;
          }
        },
        emitSave(book){
          let editBanner =  this.bannerList[this.uploadIndex];
          if(book!=null){
            if(this.baseUtil.isBlank(editBanner.imageUrl)) editBanner.imageUrl = book.bannerImage;
            editBanner.bookId = book.id;
            editBanner.linkText = book.title;
            editBanner.defaultText = book.title;
          }else{
            if(this.baseUtil.isNotBlank(editBanner.id)){
              editBanner.linkText = editBanner.defaultText;
            }
          }
          this.dialogVisible = false;
        },
        onSortChange(){
          this.$nextTick(()=>{
            this.bannerList.sort((a,b)=>{ return a.showOrder - b.showOrder});
          })
        },
        onUpClick(index){
          this.uploadIndex = index;
        },
        handleAvatarSuccess(res, file) {
          let banner = this.bannerList[this.uploadIndex]
          banner.imageUrl = res.data;//URL.createObjectURL(file.raw);
          this.uploadIndex = -1;
        },
        beforeAvatarUpload(file) {
          const isJPG = file.type === 'image/jpeg';
          const isPNG = file.type === 'image/png';
          const isLt500KB = file.size / 1024  < 500;
          if (!isJPG && !isPNG) {
            this.$alert('图片格式错误,请检查后重新上传。',{type:'warning'});
          }
          if (!isLt500KB) {
            this.$alert('图片大小不合适,请上传小于100KB的图片',{type:'warning'});
          }
          return (isJPG||isPNG) && isLt500KB;
        },
        autoUpdate(){
          this.$emit("update:banners",this.bannerList)
        },
      },
      mounted(){
        let bannerList = this.baseUtil.modelCopy(this.banners);
        if(bannerList.length > 0){
          bannerList.map(m=> {
            if(m.linkType == 1){
              m.linkText = m.book.title;
              m.defaultText =  m.book.title;
            }else{ m.linkText = m.linkUrl};
          });
          this.bannerList = bannerList;
        }else{
          this.bannerList = bannerList;
          this.onItemAdd();
        }
      }
    }
</script>

<style>
  .template-banner-list .banner-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    text-align: center;
    width:500px;
    height:201px;
  }
  .template-banner-list .banner-uploader .el-upload:hover {
    border-color: #409EFF;
  }
</style>
<style scoped>
  .template-banner-list,.template-banner-list li{ list-style:none; margin:0;padding:0;}
  .template-banner-list{
    width:500px;
  }
  .banner-item{
    position: relative;
  }
  .banner-close{
    position: absolute;
    z-index: 1001;
    right:0px;
    top:0px;
    cursor: pointer;
    font-size: 16px;
    color:#555;
  }
  .banner-close:hover{
    color:#333;
  }

  .banner-uploader{
    margin-bottom:16px;
  }
  .banner-uploader-icon {
    margin:50px auto 0 auto;
    font-size: 50px;
    color: #8c939d;
    text-align: center;
  }
  .banner-image {
    width: 500px;
    height: 200px;
    display: block;
  }
  .banner-add{
    cursor: pointer;
    font-size:13px;
    font-weight: bolder;
    color:#37BCA0;
  }
</style>
